#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import sys
import re
import fileutils

try:
    from tkinter import *
except ImportError:  #Python 2.x
    PythonVersion = 2
    from Tkinter import *
    from tkFont import Font
    from ttk import *
    #Usage:showinfo/warning/error,askquestion/okcancel/yesno/retrycancel
    from tkMessageBox import *
    #Usage:f=tkFileDialog.askopenfilename(initialdir='E:/Python')
    #import tkFileDialog
    #import tkSimpleDialog
else:  #Python 3.x
    PythonVersion = 3
    from tkinter.font import Font
    from tkinter.ttk import *
    from tkinter.messagebox import *
    #import tkinter.filedialog as tkFileDialog
    #import tkinter.simpledialog as tkSimpleDialog    #askstring()

cwd = os.getcwd()

class GUI():
    def __init__(self, wind, walkdirs):
        self.wind = wind
        self.walkdirs = walkdirs
        pass

    def init(self):
        self.e = Variable()
        self.entry = Entry(self.wind, textvariable=self.e, width=800)
        self.entry.pack()

        self.check = Button(self.wind, text=u'---------点我搜索---------', command=self.click_check, width=800)
        self.check.pack()

        '''
        文本控件：用于显示多行文本
        '''
        # 创建滚动条
        scroll = Scrollbar()
        self.text = Text(self.wind, width=800, height=100)
        # side放到窗体的哪一侧,  fill填充
        scroll.pack(side=RIGHT, fill=Y)
        self.text.pack(side=LEFT, fill=Y)
        # 关联
        scroll.config(command=self.text.yview)
        self.text.config(yscrollcommand=scroll.set)
        self.text.pack()
        #text.insert(INSERT, "")
        pass

    def click_check(self):
        s = self.e.get()
        if s == '':
            self.clear()
            self.result(u'搜索的字符串为空\n')
            return
        self.clear()
        if s.endswith('.csb') or s.endswith('.csd'):
            s = s.replace('.csb', '.csd')
            s = s.replace('/', '\\')
            self.check_xml(s)
            return
        for dir in self.walkdirs:
            fileutils.walkfile(dir, self.start_check)
            self.result("\n--------------------------------------------------------------------\n\n")
        pass

    def start_check(self, file):
        f = open(file, "rb")
        c = 0
        s = self.e.get()
        s = s.encode(encoding="utf-8")
        for line in f:
            c = c + 1
            if line.find(s) != -1:
                #print("%s line[%d]" % (file, c))
                str = "%s line[%d]\n" % (file, c)
                self.result(str)
        f.close()
        pass

    def check_xml(self, xml):
        if len(walkdirs) <= 0:
            return
        dir = walkdirs[0]
        find = False
        def __walk__(file):
            if xml in file:
                find = True
                self.start_check_xml(file)
            pass
        fileutils.walkfile(dir, __walk__)
        if find == False:
            self.result('%s is not find .' % xml)
        pass

    def start_check_xml(self, file):
        f = open(file, "rb")
        s = f.read()
        f.close()
        # pattern = r'.(jp(e)?g|png|plist)$'
        pattern = 'Path="(.*?)"'
        m = re.findall(pattern, s, re.S)
        if m:
            mm = set(m)
            for ss in mm:
                self.result(ss + '\n')
        else:
            self.result('not match line .')
        self.result("\n--------------------------------------------------------------------\n\n")
        pass

    def result(self, str):
        self.text.insert(INSERT, str)
        pass

    def clear(self):
        self.text.delete(0.0, END)

if __name__ == '__main__':
    args = sys.argv

    walkdirs = []
    if len(args) > 2:
        for i in range(1, len(args)):
            print(args[i])
            walkdirs.append(args[i])

    wind = Tk()
    wind.title(u'搜索字符串 用于搜索代码和UI编辑文件词汇')
    wind.geometry("800x400")
    GUI(wind, walkdirs).init()
    wind.mainloop()

    pass